"""
User Settings Model
用户设置模型 - 用户偏好设置和限制配置
"""

import uuid
import json

from sqlalchemy import Column, String, DateTime, Integer, Boolean, Text, ForeignKey, JSON
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from ..core.database import Base


class UserSettings(Base):
    """用户设置模型"""

    __tablename__ = "user_settings"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id = Column(
        UUID(as_uuid=True), 
        ForeignKey("users.id", ondelete="CASCADE"), 
        nullable=False, 
        unique=True,
        index=True
    )

    # 界面偏好设置
    theme = Column(String(20), default="light")  # light, dark, auto
    language = Column(String(10), default="zh-CN")  # zh-CN, en-US
    timezone = Column(String(50), default="Asia/Shanghai")
    
    # 内容生成默认设置
    default_content_type = Column(String(20), default="image")  # image, video, audio
    default_ai_provider = Column(String(20), default="doubao")  # doubao, ali, openai
    default_image_size = Column(String(10), default="1K")  # 512, 1K, 2K, 4K
    default_video_duration = Column(Integer, default=5)  # 秒
    default_audio_duration = Column(Integer, default=30)  # 秒
    default_quality = Column(String(10), default="high")  # low, medium, high
    
    # 高级生成参数（JSON存储）
    default_generation_params = Column(JSON, default=dict)
    
    # 通知设置
    email_notifications = Column(Boolean, default=True)
    push_notifications = Column(Boolean, default=True)
    notification_frequency = Column(String(20), default="immediate")  # immediate, daily, weekly
    
    # 隐私设置
    profile_visibility = Column(String(20), default="public")  # public, friends, private
    show_email = Column(Boolean, default=False)
    allow_data_collection = Column(Boolean, default=True)
    
    # 使用限制自定义设置
    custom_daily_limit = Column(Integer, nullable=True)  # 覆盖系统默认限制
    custom_storage_limit_mb = Column(Integer, nullable=True)
    auto_cleanup_enabled = Column(Boolean, default=True)
    cleanup_days = Column(Integer, default=30)  # 自动清理天数
    
    # 快捷操作设置
    quick_actions = Column(JSON, default=list)  # 用户自定义快捷操作
    favorite_templates = Column(JSON, default=list)  # 收藏的模板ID列表
    
    # 实验功能开关
    beta_features_enabled = Column(Boolean, default=False)
    experimental_features = Column(JSON, default=dict)  # 实验功能开关
    
    # 时间戳
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())

    # 关系
    user = relationship("User", back_populates="settings")

    def __repr__(self):
        return f"<UserSettings(user_id={self.user_id}, theme={self.theme})>"

    @property
    def effective_daily_limit(self) -> int:
        """获取有效的每日生成限制"""
        return self.custom_daily_limit if self.custom_daily_limit is not None else None

    @property
    def effective_storage_limit_mb(self) -> int:
        """获取有效的存储限制"""
        return self.custom_storage_limit_mb if self.custom_storage_limit_mb is not None else None

    def get_generation_params(self) -> dict:
        """获取生成参数字典"""
        params = {
            "content_type": self.default_content_type,
            "ai_provider": self.default_ai_provider,
            "quality": self.default_quality,
        }
        
        if self.default_content_type == "image":
            params["size"] = self.default_image_size
        elif self.default_content_type == "video":
            params["duration"] = self.default_video_duration
        elif self.default_content_type == "audio":
            params["duration"] = self.default_audio_duration
            
        # 合并用户自定义参数
        params.update(self.default_generation_params or {})
        return params

    def update_quick_action(self, action_id: str, action_config: dict) -> None:
        """更新快捷操作"""
        quick_actions = self.quick_actions or []
        
        # 查找是否已存在
        for i, action in enumerate(quick_actions):
            if action.get("id") == action_id:
                quick_actions[i] = action_config
                break
        else:
            quick_actions.append(action_config)
            
        self.quick_actions = quick_actions

    def remove_quick_action(self, action_id: str) -> bool:
        """移除快捷操作"""
        quick_actions = self.quick_actions or []
        original_length = len(quick_actions)
        
        self.quick_actions = [
            action for action in quick_actions 
            if action.get("id") != action_id
        ]
        
        return len(self.quick_actions) < original_length

    def add_favorite_template(self, template_id: str) -> None:
        """添加收藏模板"""
        favorites = self.favorite_templates or []
        if template_id not in favorites:
            favorites.append(template_id)
            self.favorite_templates = favorites

    def remove_favorite_template(self, template_id: str) -> bool:
        """移除收藏模板"""
        favorites = self.favorite_templates or []
        if template_id in favorites:
            favorites.remove(template_id)
            self.favorite_templates = favorites
            return True
        return False

    def is_favorite_template(self, template_id: str) -> bool:
        """检查是否为收藏模板"""
        return template_id in (self.favorite_templates or [])